import React, { useState, useEffect, useMemo, memo, useCallback } from 'react'

const Son = memo(
    ({ person, onChange }) => {
        return (
            <div>
                劳资是子组件
                <br />
                {JSON.stringify(person)}
                <br />
                <input type="text" onChange={onChange} />
                {console.log("son rendered")}
            </div>
        )
    }
)

function UseCallbackDemo() {
    const [count, setCount] = useState(0)
    const [age, setAge] = useState(20)

    // const person = {
    //     name: "张全蛋",
    //     age
    // }

    /* 自带缓存的数据 */
    const person = useMemo(
        () => {
            return { name: "张全蛋", age }
        },
        [age]
    )

    // console.log("before");
    // const onChildInputChange = e => {
    //     console.log(e.target.value);
    // }
    // console.log("after");

    // 将函数视为数据去缓存也是OK的
    // const onChildInputChange = useMemo(
    //     () => e => {
    //         console.log(e.target.value);
    //     },
    //     []
    // )

    // 缓存函数（刻意将数据的缓存与函数的缓存分开）
    const onChildInputChange = useCallback(
        e => {
            console.log(e.target.value);
        },
        []
    )

    return (
        <div>
            {count} {" "}
            <button onClick={() => {
                setCount(count + 1)
            }}>+</button>
            <br />

            {age} {" "}
            <button onClick={() => {
                setAge(age + 1)
            }}>age++</button>

            <br />
            <Son person={person} onChange={onChildInputChange} />
            {console.log("parent rendered")}

        </div>
    )
}

export default UseCallbackDemo
